package com.tz.liveplayermodule;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baijiayun.glide.Glide;
import com.baijiayun.glide.load.resource.bitmap.CircleCrop;
import com.baijiayun.glide.load.resource.bitmap.RoundedCorners;
import com.baijiayun.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.tz.liveplayermodule.bean.GetHistoryBean;
import com.tz.liveplayermodule.util.CommonUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HistoryVideoActivity extends Activity {
    private HistoryAdapter historyAdapter;
    private List<GetHistoryBean.ResultBean> resultBeans;
    private LinearLayout bottom_layout;
    private TextView choose_all, delete, title;
    private ListView local_video_list_view;
    private AlertDialog progressDialog;

    @SuppressLint("ResourceType")
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            //如果系统回收的Activity， 但是系统却保留了Fragment， 当Activity被重新初始化， 此时， 系统保存的Fragment 的getActivity为空，
            //所以要移除旧的Fragment ， 重新初始化新的Fragment
            String FRAGMENTS_TAG = "android:support:fragments";
            savedInstanceState.remove(FRAGMENTS_TAG);
        }
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_history_video);

        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.yellow));

        title = (TextView) findViewById(R.id.title);

        findViewById(R.id.back_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        local_video_list_view = (ListView) findViewById(R.id.local_video_list_view);
        bottom_layout = (LinearLayout) findViewById(R.id.bottom_layout);
        choose_all = (TextView) findViewById(R.id.choose_all);
        delete = (TextView) findViewById(R.id.delete);

        title.setText("观看历史");
        getHistory();
    }

    public class HistoryAdapter extends BaseAdapter {
        private LayoutInflater mLayoutInflater;
        private List<GetHistoryBean.ResultBean> mIntegralList;
        private Context mContext;
        private int mImgWidth, mImgHeight;

        public HistoryAdapter(Context context, List<GetHistoryBean.ResultBean> integralList) {
            mLayoutInflater = LayoutInflater.from(context);
            mContext = context;
            mIntegralList = integralList;
        }

        @Override
        public int getCount() {
            return mIntegralList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                view = mLayoutInflater.inflate(R.layout.item_history_video, null);
                holder = new ViewHolder();
                holder.class_img = (ImageView) view.findViewById(R.id.class_img);
                holder.title = (TextView) view.findViewById(R.id.title);
                holder.message = (TextView) view.findViewById(R.id.message);
                holder.progress_bar = (ProgressBar) view.findViewById(R.id.progress_bar);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            String progress = mIntegralList.get(i).getProgress();
            if (!CommonUtils.isEmpty(progress)) {
                int progressInt = Integer.parseInt(progress);
                if (progressInt > 60) {
                    progress = progressInt / 60 + "分钟";
                } else {
                    progress = progressInt + "秒";
                }
            } else {
                progress = "0分钟";
            }
            //设置图片圆角角度
            RoundedCorners roundedCorners = new RoundedCorners(10);
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(300, 300);

            Glide.with(mContext).load(mIntegralList.get(i).getTitlepic()).apply(options).into(holder.class_img);
//            Glide.with(mContext).load(mIntegralList.get(i).getTitlepic()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(holder.class_img);
            holder.title.setText(mIntegralList.get(i).getTitle());
            holder.message.setText("课时" + mIntegralList.get(i).getCurrent_count() + "/" + mIntegralList.get(i).getCount() + "节 已观看至" + progress);
            holder.progress_bar.setProgress(Integer.parseInt(mIntegralList.get(i).getProgress()));

            return view;
        }

        private class ViewHolder {
            ImageView class_img;
            TextView title;
            TextView message;
            ProgressBar progress_bar;
        }

    }

    /**
     * 获取视频观看历史记录
     */
    private void getHistory() {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//        formBody.add("token", "9453eaa008524a665ac51c08e4d68273");
        formBody.add("token", getIntent().getStringExtra("token"));
        Request request = new Request.Builder()//创建Request 对象。
                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=live&a=getHistory")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgressDialog();
                HistoryVideoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(HistoryVideoActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                cancelProgressDialog();
                assert response.body() != null;
                String responseStr = response.body().string();
                System.out.println("getHistory==:" + responseStr);
                Gson gson = new Gson();
                final GetHistoryBean getNodesBean = gson.fromJson(responseStr, GetHistoryBean.class);
                if (getNodesBean.getCode().equals("200")) {

                    HistoryVideoActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            resultBeans = new ArrayList<>();
                            resultBeans.addAll(getNodesBean.getResult());
                            historyAdapter = new HistoryAdapter(HistoryVideoActivity.this, resultBeans);
                            local_video_list_view.setAdapter(historyAdapter);

                            local_video_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    Intent intent = new Intent(HistoryVideoActivity.this, LiveRoomNewActivity.class);
//                                    Intent intent = new Intent(HistoryVideoActivity.this, LiveRoomActivity.class);
                                    intent.putExtra("token", getIntent().getStringExtra("token"));
                                    intent.putExtra("app", getIntent().getStringExtra("app"));
                                    intent.putExtra("major_type", getIntent().getStringExtra("major_type"));
                                    intent.putExtra("new",  resultBeans.get(i).getNewX());
                                    intent.putExtra("item_title", resultBeans.get(i).getTitle());
                                    intent.putExtra("course_id",  resultBeans.get(i).getCourse_id());
                                    intent.putExtra("urlTitle", getIntent().getStringExtra("urlTitle"));
                                    intent.putExtra("username", getIntent().getStringExtra("username"));
                                    startActivity(intent);
                                }
                            });
                        }
                    });
                }
            }
        });
    }


    /**
     * 加载框显示
     **/
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void buildProgressDialog(boolean cancelable) {
        if (progressDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(HistoryVideoActivity.this);
            builder.setView(R.layout.item_progress_dialog);
            builder.setCancelable(cancelable);
            progressDialog = builder.create();
            progressDialog.show();
        } else {
            progressDialog.show();
        }
    }

    /**
     * 加载框消失
     **/
    public void cancelProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}
